//
//  CommunityUserViewController.m
//  Four_Fit_New
//
//  Created by lanou on 16/7/16.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "CommunityUserViewController.h"
#import "UserDetailedModel.h"
#import "UserHeaderView.h"
#import "Community.h"
#import "CommunityCell.h"
#import "CommentViewController.h"
#import "UIScrollView+ScalableCover.h"

@interface CommunityUserViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** 存放用户信息 */
@property (nonatomic, strong) NSMutableArray *userInfoArray;
/** 存放用户动态 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** <#注释#> */
@property (nonatomic, assign) NSInteger page;
/** <#注释#> */
@property (nonatomic, strong) UserHeaderView *headerView;
/** <#注释#> */
@property (nonatomic, strong) UILabel *titleLabel;
/** 记录背景图片的随机数 */
@property (nonatomic, assign) NSInteger imageIndex;
/** 导航栏背景图 */
@property(nonatomic,strong)UIImageView *barImageView;

@end


static NSString *const cellID = @"community_cell";
@implementation CommunityUserViewController

- (NSMutableArray *)userInfoArray {
    if (!_userInfoArray) {
        _userInfoArray = [NSMutableArray array];
    }
    return _userInfoArray;
}
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UserHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [UserHeaderView userHeaderView];
        _headerView.size = CGSizeMake(kWidth, 200);
    }
    return _headerView;
}
- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 24)];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:17];
        
    }
    return _titleLabel;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    //修改导航栏颜色
    // 改变成透明色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.barImageView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CommunityCell" bundle:nil] forCellReuseIdentifier:cellID];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.page = 1;
    
    [self loadUserInfoData];
    [self loadDynamicData];
    [self setUpRefresh];
    [self setUpHeaderView];
    
    
}

- (void)loadUserInfoData {
    
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"userid"] = @"5784da4c4925c70c581758a9";
    parame[@"lookforid"] = self.userID;
    parame[@"tokenid"] = @"tokenid_undefined";
    parame[@"ismy"] = @"false";
    
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://ws.sythealth.com/ws/fit/v4_3/user/getpersonalspaceinfo" parameters:parame method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",dic[@"data"]);
        
        UserDetailedModel *model = [[UserDetailedModel alloc] init];
        [model setValuesForKeysWithDictionary:dic[@"data"]];
        [self.userInfoArray addObject:model];
        
    } updateUI:^{
        
        
        //设置headerView上面的内容
        self.headerView.model = self.userInfoArray[0];
        
        self.tableView.tableHeaderView = self.headerView;
        
        [self.tableView reloadData];
    }];
    
    
}

#pragma mark - 上拉加载更多数据
- (void)setUpRefresh {

      MJRefreshBackGifFooter *gifFooter = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
          self.page += 1;
          
          [self loadDynamicData];
      }];

    self.tableView.mj_footer = gifFooter;

    NSMutableArray *imageArray = [NSMutableArray array];
    for (int i = 1; i < 34; i++) {
        NSString *str = [NSString stringWithFormat:@"46-120HQ24947－%d（被拖移）.tiff",i];
        UIImage *image = [UIImage imageNamed:str];
        [imageArray addObject:image];
    }
    gifFooter.labelLeftInset = -15;
    [gifFooter setImages:imageArray duration:0.5 forState:MJRefreshStateRefreshing];
}

- (void)loadDynamicData {
    
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"userid"] = @"5784da4c4925c70c581758a9";
    parame[@"feeduserid"] = self.userID;
    parame[@"tokenid"] = @"tokenid_undefined";
    parame[@"page"] = @(self.page);
    
    [[QZRequestManager sharedManager]fetchDataWithUrl:@"http://ws.sythealth.com/ws/fit/v4_3/feed/getfeedbyuser" parameters:parame method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dic);
        for (NSDictionary *smallDic in dic[@"data"]) {
            Community *comm = [[Community alloc] init];
            [comm setValuesForKeysWithDictionary:smallDic];
            [self.dataArray addObject:comm];
        }
        
    } updateUI:^{
        
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    }];
}

- (void)setUpHeaderView {
    
    
    self.titleLabel.text = self.userName;
    self.navigationItem.titleView = self.titleLabel;
    self.navigationItem.titleView.hidden = YES;
    self.navigationController.navigationBar.translucent = YES;
//    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    
    self.imageIndex = arc4random() % 9 + 1;
    //设置tableview的背景图片
    [self.tableView addScalableCoverWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"image_%ld.jpg",self.imageIndex]]];
    //设置导航栏背景图片  bar image
    self.barImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -20, kWidth, 64)];
    self.barImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"image_%ld.jpg",self.imageIndex]];
    self.barImageView.clipsToBounds = YES;
    self.barImageView.contentMode = UIViewContentModeBottom;
    self.barImageView.alpha = 0;
    [self.navigationController.navigationBar insertSubview:self.barImageView atIndex:0];
    //添加模糊视图
    UIVisualEffectView *visView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visView.frame = self.barImageView.bounds;
    [self.barImageView addSubview:visView];
    
    
   
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommunityCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.community = self.dataArray[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Community *comm = self.dataArray[indexPath.row];
    return comm.cellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommentViewController *commentVc = [[CommentViewController alloc] init];
    
    commentVc.noteid = [self.dataArray[indexPath.row] ID];
    
    [self.navigationController pushViewController:commentVc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
     if(scrollView.contentOffset.y < 200 - 64){
        self.navigationItem.titleView.hidden = NO;
        self.barImageView.alpha = 0;
        self.headerView.visualView.alpha = scrollView.contentOffset.y / 115.0;
//         NSLog(@"%f",scrollView.contentOffset.y);
        self.titleLabel.alpha = scrollView.contentOffset.y / 115.0;
    }
    if (scrollView.contentOffset.y >= 200 - 64) {
        self.barImageView.alpha = 1;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
